<template>
  <view class="avatar-section">
    <view class="avatar-wrapper" @click="chooseAvatar">
      <image v-if="!!modelValue" :src="modelValue" class="avatar" />
      <view v-else class="avatar-placeholder">
        <wd-icon name="fill-camera" size="28" color="#999" />
      </view>
    </view>
    <view class="avatar-tip"></view>
    <wd-img-cropper v-model="avatarShow" :img-src="originalSrc" @confirm="handleAvatarConfirm" />
  </view>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from "vue";
import FileAPI, { type FileInfo } from "@/api/file";

const props = defineProps({
  modelValue: String,
});
const emits = defineEmits(["update:modelValue"]);

const avatarShow = ref(false);
const originalSrc = ref("");

function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      originalSrc.value = res.tempFilePaths[0];
      avatarShow.value = true;
    },
  });
}

function handleAvatarConfirm(event: any) {
  const { tempFilePath } = event;
  uni.showLoading({ title: "上传中..." });
  FileAPI.upload(tempFilePath)
    .then((fileInfo: FileInfo) => {
      emits("update:modelValue", fileInfo.url);
      uni.hideLoading();
      uni.showToast({ title: "上传成功", icon: "success" });
    })
    .catch(() => {
      uni.hideLoading();
      uni.showToast({ title: "头像上传失败", icon: "none" });
    });
}
</script>

<style scoped>
.avatar-section {
  display: flex;
}
.avatar-wrapper {
  width: 200rpx;
  height: 200rpx;
  overflow: hidden;
  background: #f5f5f5;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
  background: #165dff;
  border-radius: 50%;
  padding: 6rpx;
}
.avatar-tip {
  margin-top: 8rpx;
  color: #999;
  font-size: 24rpx;
}
</style>
